
//
// 110603 - AH - (Garage) Created.
// 110604 - AH - (Bybanen) Missing java doc added.
//

package org.soekrat.engine;

import org.soekrat.engine.util.LCS;
import org.soekrat.engine.util.StringMetric;

/**
 * <p>
 *   {@link SoekratNameMatcher} that matches if exactly matches or all starred
 *   words are matched.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
public final class DefaultSoekratNameMatcher extends SoekratNameMatcher 
{
  private StringMetric m_metric=new LCS();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public DefaultSoekratNameMatcher(){}
  
  public StringMetric getStringMetric(){ return m_metric; }
  
  // Specified in SoekratNameMatcher.
  public boolean match(String s, SoekratName name) 
  {
    if (s==null)
    {
      throw new NullPointerException("s");
    }
    if (name==null)
    {
      throw new NullPointerException("name");
    }
    
    if (m_metric.matchIgnoreCase(s, name.getPure())) return true;
    
    //if (s.equalsIgnoreCase(name.getPure())) return true;
    
    String[] starred=name.getStarred();
    int n=starred.length;
    if (n>0)
    {
      int matched=0;
      
      String[] tokens=tokenize(s);
      int m=tokens.length;
      
      for (String star : starred) 
      {
        boolean found=false;
        for (int i=0; i<m && !found; i++)
        {
          String token=tokens[i];
          
          found=m_metric.matchIgnoreCase(token, star);
          //if (token.equalsIgnoreCase(star)) found=true;
        }
        if (found) matched++;
      }
      
      return matched==n;
    }
    else
    {
      return false;
    }
  }
  
  public static void main(String[] args) 
  {
    SoekratNameMatcher matcher=new DefaultSoekratNameMatcher();
    
    String s="Arne* and Garage* is often associated";
    SoekratName name=new SoekratName(s);
    
    System.out.println(matcher.match("Garage is a pub and Arne is a programmer", name));
    System.out.println(matcher.match("Garage is a pub and Tom is a programmer", name));
    System.out.println(matcher.match("Bien is a pub and Tom is a programmer", name));
    System.out.println(matcher.match("Arne and Garage is often associated", name));
    
    System.out.println("====");
    
    String s2="Laetitia is absolute loco about wine";
    SoekratName name2=new SoekratName(s2);
    System.out.println(matcher.match("Laetitia is absolute loco about wine", name2));
    System.out.println(matcher.match("Arne and Garage is often associated", name2));
  }

}
